package com.example.petproject.controller;

import com.example.petproject.config.AliYunSmsConfig;
import com.example.petproject.entity.vo.ReturnStatusEnum;
import com.example.petproject.entity.vo.ReturnVO;
import com.example.petproject.service.third.ali.AliYunSmsService;
import com.example.petproject.util.MathUtils;
import com.example.petproject.util.PetUmsUtils;
import io.swagger.v3.core.util.PathUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 包名称：com.example.petproject.controller
 * 类名称：UmsSmsController
 * 类描述：短信控制器
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月04日 13:43
 **/
@RestController
@Tag(name = "发送短信")
public class UmsSmsController {

    /**
     * 手机号正则表达式
     */
    private String regular = "^\\d{11}$";

    private static final Logger log = LoggerFactory.getLogger(UmsSmsController.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AliYunSmsService aliYunSmsService;

    @Resource
    private AliYunSmsConfig aliYunSmsConfig;

    /**
     * 发送短信验证码
     *
     * @param phone    手机号
     * @param codeType 短信类型
     * @return 提示信息
     */
    @PostMapping(value = "/ums/sms/sendSms")
    public ReturnVO<Void> sendSms(String phone, Integer codeType) {
        //1、校验手机号是否合法，一般通过正则表达式验证
        boolean checkResult = phone.matches(regular);
        if (!checkResult) {
            log.warn("手机号错误：{}",phone);
            return ReturnVO.error(ReturnStatusEnum.FAIL_UMS_PHONE_ERROR);
        }

        //2、校验发送时间间隔是否小于60秒，先通过手机号查询redis是否存在验证码,判断验证码的生成事件和当前间隔的时间
        String codeKey = PetUmsUtils.generateSmsRedisKey(codeType,phone);
        //取出当前手机号对应的Key的剩余的过期时长
        Long expire = stringRedisTemplate.getExpire(codeKey);
        if (expire!=null&&expire>=240) {
            return ReturnVO.error(ReturnStatusEnum.FAIL_UMS_SMS_CODE_TOO_FAST);
        }

        //3、先生成验证码
        String captcha = MathUtils.random();
        log.info("登录验证码：{}",captcha);
        //4、将生成的验证码存入redis
        stringRedisTemplate.opsForValue().set(codeKey,captcha,5,TimeUnit.MINUTES);
        //5、调用service完成发送
        String templateParam="{\"code\":"+captcha+"}";
        if (aliYunSmsConfig.getEnable()) {
            Boolean sendResult = aliYunSmsService.sendSms(phone, aliYunSmsConfig.getCaptchaTemplateCode(), templateParam);
            //6、根据调用结果响应给前端
            if (sendResult) {
                return ReturnVO.ok();
            }
            return ReturnVO.error(ReturnStatusEnum.FAIL);
        }
        return ReturnVO.ok();
    }

}
